package com.gin.no_gay_alliance.customview;


import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.enums.ItemType;
import com.gin.nga.enums.ItemUseType;
import com.gin.nga.exception.NgaClientException;
import com.gin.nga.exception.NgaException;
import com.gin.nga.params.nuke.item.ItemBuyParam;
import com.gin.nga.params.nuke.item.ItemUseParam;
import com.gin.nga.response.body.BaseMessageBody;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.databinding.DialogItemBinding;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.TextViewTarget;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.ItemModel;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * 道具图标
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/7 15:38
 **/
public class ItemView extends androidx.appcompat.widget.AppCompatTextView implements View.OnClickListener, DialogInterface.OnClickListener, Callback<BaseMessageBody> {
    int size = 30;
    @NonNull
    private ItemModel itemModel;
    @NonNull
    private Params params;
    /**
     * 购买数量
     */
    private int count = 1;


    public ItemView(@NonNull Context context) {
        super(context);
    }

    public ItemView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ItemView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 加载一个道具数据
     *
     * @param itemModel 道具数据
     * @param params    确认后执行操作的参数
     */
    public void init(@NonNull ItemModel itemModel, @NonNull Params params) {
        this.itemModel = itemModel;
        this.params = params;
        setText(itemModel.name);
        setOnClickListener(this);
        // 加载icon
        loadIcon(this, this.size, 1, itemModel.icon);
    }

    @Override
    public void onClick(View v) {
        DialogItemBinding b = MyApplication.app.managerFactory.getViewBindingManager().getDialogView(DialogItemBinding.class, getContext());

        // 图标
        loadIcon(b.tvName, this.size, 0, itemModel.icon);
        b.tvName.setText(String.format(Locale.CHINA, "%s (%d个)", itemModel.name, itemModel.count));
        // 单价
        b.tvMoney.setText(String.format("单价: %s", itemModel.money));
        ViewUtils.setGone(ObjectUtils.isEmpty(itemModel.money), b.tvMoney);
        // 创建时间
        b.tvTime.setText(String.format("创建时间: %s", itemModel.time));
        // 类型
        if (itemModel.type != null) {
            b.tvType.setText(String.format("道具类型: %s", itemModel.type.name));
            b.tvType.setVisibility(VISIBLE);
        } else {
            b.tvType.setVisibility(GONE);
        }
        // 描述
        b.tvDescription.setText(String.format("道具描述: %s", itemModel.description));
        // 购买限制
        b.tvPermission.setText(String.format("购买限制: %s", itemModel.permissionBuyStore));
        ViewUtils.setGone(ObjectUtils.isEmpty(itemModel.permissionBuyStore), b.tvPermission);
        // 购买限制
        if (itemModel.buffLast != null) {
            b.tvLast.setText(String.format("持续时长: %s 天", TimeUnit.SECONDS.toDays(itemModel.buffLast)));
            b.tvLast.setVisibility(VISIBLE);
        } else {
            b.tvLast.setVisibility(GONE);
        }

        // 显示状态


        // 购买操作选择数量
        if (params.action == Action.BUY) {
            b.numberPicker.setValue(count);
            b.numberPicker.setMinValue(1);
            b.numberPicker.setMaxValue(10);
            b.numberPicker.setOnValueChangedListener((picker, oldVal, newVal) -> count = newVal);

            ViewUtils.setGone(true, b.tvTargetReply, b.tvTargetUser);
            ViewUtils.setGone(false, b.tvBuyCount, b.numberPicker);

        } else {
            if (params.userId != null && itemModel.type == ItemType.TO_USER) {
                // 对人道具
                ViewUtils.setGone(true, b.tvTargetReply, b.tvBuyCount, b.numberPicker);
                ViewUtils.setGone(false, b.tvTargetUser);

                b.tvTargetUser.setText(String.format(Locale.CHINA, "对用户 %d 使用", params.userId));
            } else if (params.topicId != null && params.replyId != null && itemModel.type == ItemType.TO_REPLY) {
                // 对贴道具
                ViewUtils.setGone(true, b.tvTargetUser, b.tvBuyCount, b.numberPicker);
                ViewUtils.setGone(false, b.tvTargetReply);

                b.tvTargetReply.setText(String.format(Locale.CHINA, "对主题 %d 的回复 %d 使用", params.topicId, params.replyId));
            } else {
                ViewUtils.setGone(true, b.tvTargetReply, b.tvTargetUser, b.tvBuyCount, b.numberPicker);
            }
        }
        boolean showPositiveButton = params.action != Action.CHECK || itemModel.type == ItemType.MEDAL;
        AlertDialog dialog = AlertDialogUtils.showConfirm(getContext(), buildDialogTitle(), null, b.getRoot(), showPositiveButton ? this : null);

        if (itemModel.type == ItemType.MEDAL) {
            Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            button.setText("佩戴/取下");
        }
        dialog.setOnDismissListener(d -> {
            // 关闭时移除弹窗
            ViewGroup parent = (ViewGroup) b.getRoot().getParent();
            parent.removeView(b.getRoot());
        });
    }

    /**
     * 点击确认按钮时的操作
     */
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // 购买并使用道具
        if (params.action == Action.BUY_USE) {
            MyApplication.app.managerFactory.getItemInventoryManager().itemUse(buildBuyUseParams(), this);
        }
        // 购买道具
        if (params.action == Action.BUY) {
            ItemBuyParam param = new ItemBuyParam(Math.toIntExact(itemModel.id), count);
            MyApplication.app.managerFactory.getItemInventoryManager().itemBuy(param, this);
        }
        // 佩戴或取下徽章
        if (params.action == Action.CHECK && itemModel.type == ItemType.MEDAL) {
            ItemUseParam param = new ItemUseParam(ItemUseType.USE_INVENTORY, itemModel.id, MyApplication.getClient().getUserId());
            MyApplication.app.managerFactory.getItemInventoryManager().itemUse(param, this);
        }
    }

    /**
     * 请求成功回调
     *
     * @param data 数据
     */
    @Override
    public void onSuccess(BaseMessageBody data) {
        MyApplication.app.handler.toast(data.getMessage());
    }


    /**
     * 处理Nga异常
     *
     * @param e 异常
     */
    @Override
    public void handleException(NgaException e) {
        Callback.super.handleException(e);
        if (e instanceof NgaClientException) {
            MyApplication.app.handler.toast(((NgaClientException) e).getReason().get(0));
        }
    }

    /**
     * 购买并使用道具的参数
     *
     * @return 参数
     */
    private ItemUseParam buildBuyUseParams() {
        if (params.isToUser()) {
            return new ItemUseParam(ItemUseType.BUY_AND_USE,
                    itemModel.id,
                    params.userId);
        }
        if (params.isToReply()) {
            return new ItemUseParam(ItemUseType.BUY_AND_USE,
                    itemModel.id,
                    params.topicId,
                    params.replyId != null ? params.replyId : 0,
                    null);
        }
        return null;
    }

    private String buildDialogTitle() {
        switch (params.action) {
            case BUY:
                return "购买道具";
            case BUY_USE:
                return "购买并使用道具";
            case USE:
                return "使用道具";
            case CHECK:
                return "查看道具";
            default:
                throw new IllegalStateException("Unexpected value: " + params.action);
        }
    }

    private void loadIcon(TextView tv, int size, int position, String icon) {
        int s = (int) (size * MyApplication.DEVICE_DENSITY_DPI / 160f);
        TextViewTarget target = new TextViewTarget(tv, position, s, s);
        Glide.with(getContext()).load(icon).error(R.drawable.ic_gift).placeholder(R.drawable.ic_gift).into(target);
    }

    public ItemModel getItemModel() {
        return itemModel;
    }

    /**
     * 点击确认按钮时执行的操作类型
     */
    public enum Action {
        /**
         * 单购买, 在用户中心:商店点击时使用, 需要用户输入数量
         */
        BUY,
        /**
         * 购买并使用, 在弹窗商店中: 在用户中心点击他人使用道具，或在主题中对回复使用道具时使用
         */
        BUY_USE,
        /**
         * 使用, 库存中道具总是使用
         */
        USE,
        /**
         * 查看
         */
        CHECK,
    }

    public static class Params {
        /**
         * 执行的操作类型
         */
        @NonNull
        public Action action;
        /**
         * 对人道具的目标
         */
        public Long userId;
        /**
         * 对贴道具的目标参数，主题id
         */
        public Long topicId;
        /**
         * 对贴道具的目标参数，回复id
         */
        public Long replyId;

        public Params(@NonNull Action action) {
            this.action = action;
        }

        public Params(@NonNull Action action, Long userId) {
            this(action, userId, null, null);
        }

        public Params(@NonNull Action action, Long topicId, Long replyId) {
            this(action, null, topicId, replyId);
        }

        private Params(@NonNull Action action, Long userId, Long topicId, Long replyId) {
            this.action = action;
            this.userId = userId;
            this.topicId = topicId;
            this.replyId = replyId;
        }

        public boolean isToReply() {
            return topicId != null && replyId != null;
        }

        public boolean isToUser() {
            return userId != null;
        }
    }
}
